package com.sacc.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.power.common.model.CommonResult;
import com.sacc.mapper.BoxAdoptedMapper;
import com.sacc.mapper.BoxCollectedMapper;
import com.sacc.pojo.BoxAdopted;
import com.sacc.pojo.BoxCollected;
import com.sacc.service.BoxAdoptedService;
import com.sacc.service.BoxCollectedService;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author 滚~韬
 * @date 2022/4/13 10:15
 */
@Service
public class BoxAdoptedServiceImpl implements BoxAdoptedService {
    @Autowired
    private BoxAdoptedMapper boxAdoptedMapper;
    @Autowired
    private BoxCollectedMapper boxCollectedMapper;
    @Autowired
    private BoxCollectedService boxCollectedService;
    /**
     * 获取已经认养的蜂箱id
     * @param openId
     * @return
     */
    @Override
    public List<Integer> getBoxIds(String openId) {
        if(boxAdoptedMapper.selectCount(new QueryWrapper<BoxAdopted>().eq("open_id",openId))>0){
            BoxAdopted boxAdopted = boxAdoptedMapper.selectById(openId);
            return Arrays.asList((Integer[]) ConvertUtils.convert(boxAdopted.getBoxId().split(","),Integer.class));
        }else {
            return Collections.EMPTY_LIST;
        }

    }
    /**
     * 确认认养蜂箱
     * @param boxAdopted
     * @return
     */
    @Override
    public CommonResult Adopt(BoxAdopted boxAdopted) {
        try{
            BoxAdopted box = boxAdoptedMapper.selectById(boxAdopted.getOpenId());
            if(box!=null){
                box.setBoxId(box.getBoxId()+","+boxAdopted.getBoxId());
                boxAdoptedMapper.updateById(box);
            }else {
                boxAdoptedMapper.insert(boxAdopted);
            }
            return new CommonResult("200","领养成功");
        }catch (Exception e){
            return new CommonResult("400","领养失败"+e.toString());
        }
    }

    @Override
    public CommonResult Adopt(String openId, String boxId) {
        try{
            BoxAdopted box = boxAdoptedMapper.selectById(openId);
            if(box!=null){
                box.setBoxId(box.getBoxId()+","+boxId);
                boxAdoptedMapper.updateById(box);
            }else {
                BoxAdopted temp =new BoxAdopted();
                temp.setBoxId(boxId);
                temp.setOpenId(openId);
                boxAdoptedMapper.insert(temp);
            }
            return new CommonResult("200","领养成功");
        }catch (Exception e){
            return new CommonResult("400","领养失败"+e.toString());
        }
    }
}
